﻿using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System.Threading;

public class NetWorkToServer
{
    private Queue<NetMsgBase> RecvMsgPool = null;
    private Queue<NetMsgBase> SendMsgPool = null;

    NetSocket ClientSocket;
    Thread SendThread;
    public NetWorkToServer(string id, ushort port)
    {
        RecvMsgPool = new Queue<NetMsgBase>();
        SendMsgPool = new Queue<NetMsgBase>();

        ClientSocket = new NetSocket();

        ClientSocket.AsynConnect(id, port, AyncConnectCallBack, AyncResvCallBack);
    }

    private void AyncConnectCallBack(bool sucess, NetSocket.ErrorSocket tmpError, string exception)
    {
        if (sucess)
        {
            SendThread = new Thread(LoopSendMsg);
            SendThread.Start();
        }
    }

    //---------------send-------------
    void LoopSendMsg()
    {
        while (ClientSocket != null && ClientSocket.IsConnected)
        {
            lock (SendMsgPool)
            {
                while (SendMsgPool.Count > 0)
                {
                    NetMsgBase tmpBody = SendMsgPool.Dequeue();
                    ClientSocket.AsynSend(tmpBody.GetNetBytes(), CallBackSend);
                }
            }
            Thread.Sleep(100);
        }
    }

    public void PutSendMsgPool(NetMsgBase msg)
    {
        lock (SendMsgPool)
        {
            SendMsgPool.Enqueue(msg);
        }
    }
    void CallBackSend(bool sucess, NetSocket.ErrorSocket error, string exception)
    {
        if (sucess)
        {
            Debug.Log("发送成功");
        }
        else
        {

        }
    }

    //----------------Receive-------------
    private void AyncResvCallBack(bool sucess, NetSocket.ErrorSocket error, string exception, byte[] bytes, string msg)
    {
        if (sucess)
        {
            PutRecvMsgToPool(bytes);
        }
        else
        {

        }
    }

    void PutRecvMsgToPool(byte[] recvMsg)
    {
        NetMsgBase msg = new NetMsgBase(recvMsg);
        RecvMsgPool.Enqueue(msg);
    }

    public void Update()
    {
        if (RecvMsgPool != null)
        {
            while (RecvMsgPool.Count > 0)
            {
                AnalysData(RecvMsgPool.Dequeue());
            }
        }
    }

    void AnalysData(NetMsgBase msg)
    {
        MsgCenter.Instance.SendToMsg(msg);
    }


    //----------------Dis connect-------------
    void CallBackDisConnect(bool sucess, NetSocket.ErrorSocket error, string exception)
    {
        if (sucess)
        {
            SendThread.Abort();
        }
    }

    public void DisConnect()
    {
        if (ClientSocket != null && ClientSocket.IsConnected)
        {
            ClientSocket.AsyncDisconnect(CallBackDisConnect);
        }
    }
}
